//
//  StopWatchCtrl.swift
//  RKTemplate
//
//  Created by zhaoke on 2023/7/24.
//

import UIKit

class StopWatchCtrl: UIViewController {
    var laps: [String] = [String]()
    var mainWatch: StopWatch = StopWatch()
    var lapWatch: StopWatch = StopWatch()
    var isplay = false
    let cellIentifier = "UITableViewCellIdentifier"
    var header: StopWatchHeader!
    var tableView: UITableView!
    //
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "秒表"
        view.backgroundColor = .white
        isplay = false
        setupView()
    }
    func setupView() {
        let topInset = rk_safeAreaTop + 64
        header = StopWatchHeader(frame: CGRect(x: 0, y: topInset, width: rk_screenWidth, height: 150))
        header.backgroundColor = .white
        view.addSubview(header!)
        let rect = view.frame
        let tableView = UITableView(frame: CGRect(x: 0, y: 150 + topInset, width: rk_screenWidth, height: rect.size.height - 150 - topInset), style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellIentifier)
        tableView.tableFooterView = UIView()
        view.addSubview(tableView)
        self.tableView = tableView
    }
    //
    func updateTimer(_ watch: StopWatch, label: UILabel) {
        watch.counter += 0.035
        var minutes = "\((Int)(watch.counter) / 60)"
        if (Int)(watch.counter / 60) < 10 {
            minutes = "0\((Int)(watch.counter / 60))"
        }
        var seconds = String(format: "%.2f", (watch.counter.truncatingRemainder(dividingBy: 60)))
        if watch.counter.truncatingRemainder(dividingBy: 60) < 10 {
            seconds = "0" + seconds
        }
        label.text = minutes + ":" + seconds
    }
    func resetTimer(_ watch: StopWatch, label: UILabel) {
        watch.timer.invalidate()
        watch.counter = 0.0
        label.text = "00:00:00"
    }
}
extension StopWatchCtrl: StopWatchHeaderDelegate {
    func stopWatchPlayAction() {
        let sender = self.header.playPauseBtn!
        sender.isSelected = !sender.isSelected
        if sender.isSelected {
            self.isplay = true
            unowned let weakSelf = self
            mainWatch.timer = Timer.scheduledTimer(withTimeInterval: 0.035, repeats: true, block: { (myTimer) in
                weakSelf.updateTimer(weakSelf.mainWatch, label: weakSelf.header.timerLab)
            })
            lapWatch.timer = Timer.scheduledTimer(withTimeInterval: 0.035, repeats: true, block: { (myTimer) in
                weakSelf.updateTimer(weakSelf.lapWatch, label: weakSelf.header.lapTimerLab)
            })
            RunLoop.current.add(mainWatch.timer, forMode: .common)
            RunLoop.current.add(lapWatch.timer, forMode: .common)
            if header.lapRestBtn!.titleLabel?.text != "Lap" {
                header.lapRestBtn.setTitle("Lap", for: .normal)
            }
        } else {
            self.isplay = false
            mainWatch.timer.invalidate()
            lapWatch.timer.invalidate()
            header.lapRestBtn!.setTitle("Reset", for: .normal)
        }
        if !header.lapRestBtn!.isEnabled {
            header.lapRestBtn!.isEnabled = true
        }
    }
    func stopWatchLapAction() {
        if self.isplay {
            if let timeLabText = header.lapTimerLab.text {
                laps.append(timeLabText)
            }
            tableView.reloadData()
            tableView.scrollToRow(at: IndexPath(row: laps.count - 1, section: 0), at: .none, animated: true)
            resetTimer(lapWatch, label: header.lapTimerLab)
            unowned let weakSelf = self
            lapWatch.timer = Timer.scheduledTimer(withTimeInterval: 0.035, repeats: true, block: { (myTimer) in
                weakSelf.updateTimer(weakSelf.lapWatch, label: weakSelf.header.lapTimerLab)
            })
            RunLoop.current.add(lapWatch.timer, forMode: .common)
        } else {
            resetTimer(mainWatch, label: header.timerLab)
            resetTimer(lapWatch, label: header.lapTimerLab)
            laps.removeAll()
            tableView.reloadData()
            header.lapRestBtn.setTitle("Lap", for: .normal)
            header.lapRestBtn.isEnabled = false
        }
    }
}
extension StopWatchCtrl: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.laps.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 45
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: self.cellIentifier)!
        cell.textLabel?.text = self.laps[indexPath.row]
        return cell
    }
   func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        // code
    }
}

